package com.example.ymm.schedu;

import cn.hutool.core.thread.ThreadUtil;
import com.example.ymm.modules1.entity.hl.ex.ExPublishGroup;
import com.example.ymm.modules1.entity.hl.ex.ExPublishPaper;
import com.example.ymm.modules1.service.hl.ex.ExPublishPaperService;
import com.example.ymm.modules1.socket.UserExWebSocket;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.SpringTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;


/**
 * 定时交卷
 */

@Service
@Slf4j
public class ExTaskScheduler {

//    @Autowired
//    ExPublishPaperService exPublishPaperService;

    private final ThreadPoolTaskScheduler taskScheduler;
    // 保存定时任务的引用，用于后续关闭
    private ScheduledFuture<?> scheduledFuture, scheduledFuture2;

    public ExTaskScheduler() {
        // 初始化任务调度器
        this.taskScheduler = new ThreadPoolTaskScheduler();
        this.taskScheduler.setPoolSize(5);
        this.taskScheduler.setThreadNamePrefix("dynamic-timer-");
        this.taskScheduler.initialize();
    }

    /**
     * 倒计时交卷
     * 启动定时器，并在指定未来时间关闭
     *
     * @param startTime 开始时间
     * @param endTime   计划关闭的时间
     */
    public void startTimerWithShutdownTime(LocalDateTime startTime, LocalDateTime endTime, ExPublishPaper publishPaper) {


        // 计算当前时间到目标关闭时间的毫秒数
        long delayMillis = startTime.until(endTime, java.time.temporal.ChronoUnit.MILLIS);
//        UserExWebSocket.broadcastCountDownPaper(publishPaper,delayMillis);

        if (delayMillis > 0) {
            System.out.println("定时器 通知交卷 已启动，计划于 " + endTime + " 关闭");
            // 使用系统默认时区
            ZoneId zoneId = ZoneId.systemDefault();
            Date date = Date.from(startTime.atZone(zoneId).toInstant());
            // 安排自动关闭任务
            scheduledFuture = taskScheduler.schedule(() -> {

                System.out.println("通知交卷：" + publishPaper.getPaperName() + ":" + DateKit.getStringNowTime());
//                System.out.println("--开始时间:"+startTime);
                /**
                 * 广播 交卷
                 */
//                try {
//                    Thread.sleep(5);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }

                /**
                 * 广播交卷
                 */
                ExPublishPaperService exPublishPaperService = SpringTool.getApplicationContext().getBean(ExPublishPaperService.class);
                ExPublishPaper userPaper = exPublishPaperService.getUserPaper("", publishPaper.getPublishPaperId());
                //修改数据状态
                exPublishPaperService.upNextGroup(userPaper);
                Integer limitTime=null;
                //通知考试结束获取排行榜信息
                if (userPaper.getStatus() == 2) {
                //    limitTime=30;
                }
                log.info("---交卷时 考试状态:"+userPaper.getStatus()+";publishPaperId:"+userPaper.getPublishPaperId()+";limitTime:"+limitTime);

                //格式化结束时间
                // 定义日期时间格式
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                // 格式化日期时间
                String endDateTime = endTime.format(formatter);

                try{
                    UserExWebSocket.broadcastSysSubmitPaper(userPaper,limitTime,endDateTime);
                }catch (Exception e){
                    log.error("----发送交卷广播异常"+e.getMessage(),e);
                }

                //通知考试结束获取排行榜信息
//                if (userPaper.getStatus() == 2) {
//                    // 启动定时任务 当前的时间的30秒后执行
//                    Date now=new Date();
//                    Date end= new Date(now.getTime() + (30*1000));
//                    System.out.println(DateKit.dateFormat(end)+"时间后关闭");
//                    //
//                    scheduledFuture2 = taskScheduler.schedule(() -> {
//                        UserExWebSocket.broadcastRankPaper(userPaper);
//                    }, end);
//                }

            }, new Date(date.getTime() + delayMillis));
        } else {
            System.out.println("关闭时间已过，定时器不会启动");
            stopTimer();
        }
    }


    /**
     * 倒计时开启下一个模块
     * 启动定时器，并在指定未来时间关闭
     *
     * @param
     * @param startTime 开始时间
     * @param endTime   计划关闭的时间
     */
    public void autoStartNextGroup(Date startTime, Date endTime, ExPublishGroup nextGroup, Integer limitTime) {
//        // 启动定时任务


        // 计算当前时间到目标关闭时间的毫秒数
        long delayMillis = endTime.getTime() - startTime.getTime();

        if (delayMillis > 0) {
            System.out.println("定时器已启动，计划于 " + DateKit.dateFormat(endTime) + " 进行下一个模块");

            // 安排自动关闭任务
            scheduledFuture = taskScheduler.schedule(() -> {
                stopTimer();
                System.out.println("下一模块计划关闭：" + LocalDateTime.now());
//                System.out.println("--开始时间:"+startTime);
                ExPublishPaperService exPublishPaperService = SpringTool.getApplicationContext().getBean(ExPublishPaperService.class);

                //修改数据状态
                exPublishPaperService.autoStartGroup(nextGroup, limitTime);
                /**
                 * 广播  start
                 */

            }, new Date(startTime.getTime() + delayMillis));
        } else {
            System.out.println("关闭时间已过，定时器不会启动");
            stopTimer();
        }
    }


    /**
     * 应用关闭时确保定时器优雅停止
     */
    @PreDestroy
    public void destroy() {
        stopTimer();
        taskScheduler.shutdown();
    }


    /**
     * 手动关闭定时器
     */
    public void stopTimer() {
        if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
            scheduledFuture.cancel(true);
            System.out.println("定时器已手动关闭");
        }
    }

}
